import store from '@/store/index'

const url = process.env.VITE_API_URL

interface options {
  url: string
  data?: object
}

export function beOver() {
  // 重新登录
  // uni.removeStorageSync('token')
  store.commit('setToken')
  uni.removeStorageSync('userInfo')
  store.dispatch('app/IM_DESTROY')
}

function get(options: options): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    let token = uni.getStorageSync('token')
    uni.request({
      url: url + options.url,
      method: 'GET',
      data: options.data,
      header: {
        'Content-Type': 'application/json',
        clientType: store.state.CLIENTTYPE,
        // Authorization: store.state.token,
        Authorization: token,
        orgId: 2
      },
      dataType: 'json',
      success: (respoones: any) => {
        if (respoones.statusCode == '200') {
          if (respoones.data.code != 0) {
            if (respoones.data.code === 401) {
              uni.hideLoading()
              uni.showToast({
                title: '您当前的登录信息已过期，即将返回登录页',
                icon: 'none',
                duration: 3000,
                success: (res) => {
                  beOver()
                  setTimeout(() => {
                    uni.reLaunch({
                      url: '/pages/login/index'
                    })
                  }, 3000)
                }
              })
              reject(respoones.data)
            } else {
              uni.showToast({
                icon: 'none',
                title: respoones.data.msg,
                duration: 2000
              })
              reject(respoones.data)
            }
          }
          return resolve(respoones.data)
        } else if (respoones.statusCode == 401) {
          uni.showToast({
            title: '您当前的登录信息已过期，即将返回登录页',
            icon: 'none',
            duration: 3000,
            success: (res) => {
              beOver()
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login/index'
                })
              }, 3000)
            }
          })
          reject()
        } else {
          reject()
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '请求失败',
          icon: 'none'
        })
        throw new Error('请求失败')
      }
    })
  })
}

function post(options: options): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    let token = uni.getStorageSync('token')
    uni.request({
      url: url + options.url,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        clientType: store.state.CLIENTTYPE,
        // Authorization: store.state.token,
        Authorization: token,
        orgId: 2
      },
      timeout: 30000,
      data: options.data,
      dataType: 'json',
      success: (respones: any) => {
        if (respones.statusCode == 200) {
          if (respones.data.code !== 0) {
            if (respones.data.code === 401) {
              uni.hideLoading()
              uni.showToast({
                title: '您当前的登录信息已过期，即将返回登录页',
                icon: 'none',
                duration: 3000,
                success: (res) => {
                  beOver()
                  setTimeout(() => {
                    uni.reLaunch({
                      url: '/pages/login/index'
                    })
                  }, 3000)
                }
              })
              reject(respones.data)
            } else {
              uni.showToast({
                icon: 'none',
                title: respones.data.msg,
                duration: 2000
              })
              reject(respones.data)
            }
          }
          return resolve(respones.data)
        } else if (respones.statusCode == 401) {
          uni.showToast({
            title: '您当前的登录信息已过期，即将返回登录页',
            icon: 'none',
            duration: 3000,
            success: (res) => {
              beOver()
              setTimeout(() => {
                uni.reLaunch({
                  url: '/pages/login/index'
                })
              }, 3000)
            }
          })
          reject()
        } else {
          reject()
        }
      },
      fail: (err) => {
        uni.showToast({
          title: '请求失败',
          icon: 'error'
        })
        reject()
        // throw new Error('请求失败');
      },
      complete: () => {}
    })
  })
}

interface uploadOptions {
  url: string
  file: any
  name?: string
}

function upload(options: uploadOptions): Promise<{} | undefined> | void {
  return new Promise<{} | undefined>((resolve, reject) => {
    uni.showLoading({
      mask: true,
      title: '上传中...'
    })
    let token = uni.getStorageSync('token')
    uni.uploadFile({
      url: url + options.url,
      header: {
        Authorization: store.state.token,
        clientType: store.state.CLIENTTYPE,
        // Authorization: token,
        orgId: 2
      },
      filePath: options.file,
      fileType: 'image',
      name: options.name || 'file',
      formData: options.formData || {},
      success: (respones: any) => {
        let res = JSON.parse(respones.data)
        if (respones.statusCode === 200) {
          if (res.code === 0) {
            resolve(res)
          } else {
            reject(res)
          }
        } else {
          reject({
            code: 500,
            msg: '上传失败'
          })
        }
      },
      fail: () => {
        reject({
          code: 500,
          msg: '上传失败'
        })
        throw new Error('上传失败')
      },
      complete: () => {
        uni.hideLoading()
      }
    })
  })
}

export default {
  get: get,
  post: post,
  upload: upload
}
